/*
 * Copyright (c) 2018 maoyan.com
 * All rights reserved.
 *
 */
package com.darren.euc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.darren.euc.dao.CommonDao;
import com.darren.euc.dao.MeetingroomOrderDao;
import com.darren.euc.dao.UserDao;
import com.darren.euc.entity.*;
import com.darren.euc.repository.*;
import com.darren.euc.service.MeetingroomOrderService;
import com.darren.euc.util.DateUtil;
import com.darren.euc.util.LocalCacheUtil;
import com.darren.euc.util.StringUtil;
import com.google.common.collect.Lists;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 在这里编写类的功能描述
 *
 * @author fangwenhao
 * @created 2018/3/13
 */
@Service
public class MeetingroomOrderServiceImpl implements MeetingroomOrderService {

    @Autowired
    private MeetingroomOrderDao meetingroomOrderDao;

    @Autowired
    private MeetingroomOrderRepository meetingroomOrderRepository;

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private MeetingRoomRepository meetingRoomRepository;

    @Autowired
    private SpaceRepository spaceRepository;

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private UserRepository userRepository;

    @Override
    @Deprecated
    public List<MeetingroomOrder> findByRoomIdAndDate(Integer roomId, String date) {

        String HQL = "from MeetingroomOrder where roomId = ? and day = ?";
        return meetingroomOrderDao.queryByCondition(HQL, roomId, new DateTime(date).toDate());
    }

    @Override
    public MeetingroomOrder save(MeetingroomOrder meetingroomOrder) {
        return meetingroomOrderDao.save(meetingroomOrder);
    }
    
    @Override
    public BigInteger getCurrentDayCount(Integer orderId) {
        return meetingroomOrderDao.getCurrentDayCount(orderId);
    }


    @Override
    @Deprecated
    public PageBean query(JSONObject requestJson, Integer pageSize, Integer currentPage) {
        Date startTime = new DateTime(requestJson.getString("startTime")).toDate();
        Date endTime = new DateTime(requestJson.getString("endTime")).toDate();
        Integer spaceId = requestJson.getInt("spaceId");
        Integer status = requestJson.getInt("status");
        String clientName = (String) requestJson.getOrDefault("clientName", "");
        String memberName = (String) requestJson.getOrDefault("memberName", "");
        String roomName = (String) requestJson.getOrDefault("roomName", "");

        List<Client> clientList;
        if (!StringUtil.isEmptyOrWhitespace(clientName)){
            clientList = clientRepository.findByCompanyNameLike("%" + clientName + "%");
        }else{
            clientList = clientRepository.findAll();
        }
        List<Member> memberList;
        if (!StringUtil.isEmptyOrWhitespace(memberName)){
            memberList = memberRepository.findByNameLike("%" + memberName + "%");
        }else {
            memberList = memberRepository.findAll();
        }
        List<Meetingroom> meetingroomList;
        if (!StringUtil.isEmptyOrWhitespace(roomName)){
            meetingroomList = meetingRoomRepository.findByMeetingroomNameLike("%" + roomName + "%");
        }else {
            meetingroomList = meetingRoomRepository.findAll();
        }
        List<MeetingroomOrder> meetingroomOrderList = Lists.newArrayList();
        if (spaceId > 0 && status > -1){
            meetingroomOrderList = meetingroomOrderRepository
                    .findByCreateTimeBetweenAndStatusAndSpaceId(new DateTime(startTime).toDate(),
                            new DateTime(endTime).toDate(), status, spaceId);
        }else if (spaceId > 0 && status == -1){
            meetingroomOrderList = meetingroomOrderRepository
                    .findByCreateTimeBetweenAndSpaceId(new DateTime(startTime).toDate(),
                            new DateTime(endTime).toDate(), spaceId);
        }else if (spaceId == 0 && status > -1){
            meetingroomOrderList = meetingroomOrderRepository
                    .findByCreateTimeBetweenAndStatus(new DateTime(startTime).toDate(),
                            new DateTime(endTime).toDate(), status);
        }else {
            meetingroomOrderList = meetingroomOrderRepository
                    .findByCreateTimeBetween(new DateTime(startTime).toDate(),
                            new DateTime(endTime).toDate());
        }
        if (clientList.isEmpty() || memberList.isEmpty() || meetingroomList.isEmpty() || meetingroomOrderList.isEmpty() ){
            return null;
        }

        List<MeetingroomOrderVO> meetingroomOrderVOList = Lists.newArrayList();
        for (MeetingroomOrder meetingroomOrder : meetingroomOrderList) {
            MeetingroomOrderVO meetingroomOrderVO = new MeetingroomOrderVO();
            meetingroomOrderVO.setOrderId(meetingroomOrder.getOrderId());
            meetingroomOrderVO.setOrderCode(meetingroomOrder.getOrderCode());
            meetingroomOrderVO.setOrderType("会议室订单");
            meetingroomOrderVO.setStatus(Integer.valueOf(meetingroomOrder.getStatus()));
            String rangeList = meetingroomOrder.getRangeList();
            List<BookTimeRange> bookTimeRanges = JSONArray.parseArray(rangeList,BookTimeRange.class);
            if(!CollectionUtils.isEmpty(bookTimeRanges)){
                meetingroomOrderVO.setBeginTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + bookTimeRanges.get(0).getTime() + ":00");
                meetingroomOrderVO.setEndTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + DateUtil.addHalfHour(bookTimeRanges.get(bookTimeRanges.size()-1).getTime()) + ":00");
                meetingroomOrderVO.setCreateTime(new DateTime(meetingroomOrder.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
            }
            if (meetingroomOrderVO.getStatus() == 1){
                meetingroomOrderVO.setMoney(meetingroomOrder.getMoney());
                meetingroomOrderVO.setRefundFee(BigDecimal.ZERO);
            }else {
                meetingroomOrderVO.setRefundFee(meetingroomOrder.getMoney());
                meetingroomOrderVO.setMoney(BigDecimal.ZERO);
                meetingroomOrderVO.setUpdateTime(new DateTime(meetingroomOrder.getUpdateTime()).toString("yyyy-MM-dd HH:mm:ss"));
            }
            Integer memberId = meetingroomOrder.getMemberId();
            List<Member> members = memberList.stream().filter(member -> member.getId().equals(memberId)).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(members)){
                continue;
            }
            meetingroomOrderVO.setMemberName(members.size()>0?members.get(0).getName():null);
            Integer roomId = meetingroomOrder.getRoomId();
            List<Meetingroom> rooms = meetingroomList.stream().filter(meetingroom -> meetingroom.getId().equals(roomId)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(rooms)){
                continue;
            }
            meetingroomOrderVO.setRoomName(rooms.size()>0?rooms.get(0).getMeetingroomName():null);
            Space space = spaceRepository.findOne(members.get(0).getSpaceId());
            meetingroomOrderVO.setSpaceName(space.getSpaceName());
            Integer clientId = members.get(0).getClientId();
            List<Client> clients = clientList.stream().filter(client -> client.getId().equals(clientId)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(clients)){
                continue;
            }
            meetingroomOrderVO.setCompanyName(clients.size()>0?clients.get(0).getCompanyName():null);
            String memList = meetingroomOrder.getMemList();
            List<Integer> memberIds = JSONArray.parseArray(memList,Integer.class);
            List<Member> memberList1 = memberRepository.findByIdIn(memberIds);
            meetingroomOrderVO.setMembers(memberList1);
            meetingroomOrderVO.setSubject(meetingroomOrder.getSubject());
            meetingroomOrderVOList.add(meetingroomOrderVO);
        }
        Integer size = meetingroomOrderVOList.size();
        PageBean pageBean = new PageBean();
        pageBean.setTotalRow(size);
        pageBean.setTotalPage(size/pageSize+1);
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(pageSize);
        pageBean.init();
        if (currentPage * pageSize >= size){
            pageBean.setList(meetingroomOrderVOList.subList((currentPage-1)*pageSize,size));
            return pageBean;
        }else{
            List<MeetingroomOrderVO> pageList = meetingroomOrderVOList.subList((currentPage-1)*pageSize,(currentPage)*pageSize);
            pageBean.setList(pageList);
            return pageBean;
        }
    }

    @Override
    public MeetingroomOrderVO queryOne(JSONObject requestJson) {
        Integer orderId = requestJson.getInt("orderId");
        return queryOne(orderId);
    }

    @Override
    public MeetingroomOrderVO queryOne(Integer orderId) {
        if (LocalCacheUtil.get("pay_status") != null && (Integer)LocalCacheUtil.get("pay_status") < 0){
            updateStatus(orderId,4);
        }
        MeetingroomOrder meetingroomOrder = meetingroomOrderRepository.findOne(orderId);
        
        MeetingroomOrderVO meetingroomOrderVO = new MeetingroomOrderVO();
        meetingroomOrderVO.setOrderId(meetingroomOrder.getOrderId());
        meetingroomOrderVO.setOrderCode(meetingroomOrder.getOrderCode());
        meetingroomOrderVO.setOrderType("会议室订单");
        meetingroomOrderVO.setStatus(meetingroomOrder.getStatus());
        meetingroomOrderVO.setPayStatus(Integer.valueOf(meetingroomOrder.getPayStatus()));
        String rangeList = meetingroomOrder.getRangeList();
        List<BookTimeRange> bookTimeRanges = JSONArray.parseArray(rangeList,BookTimeRange.class);
        if (!CollectionUtils.isEmpty(bookTimeRanges)){
            meetingroomOrderVO.setBeginTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + bookTimeRanges.get(0).getTime() + ":00");
            meetingroomOrderVO.setEndTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + DateUtil.addHalfHour(bookTimeRanges.get(bookTimeRanges.size()-1).getTime()) + ":00");
        }
        meetingroomOrderVO.setCreateTime(new DateTime(meetingroomOrder.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
        if (meetingroomOrderVO.getPayStatus() != 0){
            meetingroomOrderVO.setMoney(meetingroomOrder.getMoney());
            meetingroomOrderVO.setRefundFee(BigDecimal.ZERO);
        }else {
            meetingroomOrderVO.setRefundFee(meetingroomOrder.getMoney());
            meetingroomOrderVO.setMoney(meetingroomOrder.getMoney());
            meetingroomOrderVO.setUpdateTime(new DateTime(meetingroomOrder.getUpdateTime()).toString("yyyy-MM-dd HH:mm:ss"));
        }
        Integer memberId = meetingroomOrder.getMemberId();
        Member member = memberRepository.findOne(memberId);
        meetingroomOrderVO.setMemberName(member.getName());
        Integer roomId = meetingroomOrder.getRoomId();
        Meetingroom meetingroom = meetingRoomRepository.findOne(roomId);
        meetingroomOrderVO.setRoomName(meetingroom.getMeetingroomName());
        Space space = spaceRepository.findOne(member.getSpaceId());
        meetingroomOrderVO.setSpaceName(space.getSpaceName());
        Integer clientId = member.getClientId();
        Client client = clientRepository.findOne(clientId);
        meetingroomOrderVO.setCompanyName(client.getCompanyName());
        String memList = meetingroomOrder.getMemList();
        List<Integer> memberIds = JSONArray.parseArray(memList,Integer.class);
        List<Member> memberList1 = memberRepository.findByIdIn(memberIds);
        meetingroomOrderVO.setMembers(memberList1);
        meetingroomOrderVO.setSubject(meetingroomOrder.getSubject());
        return meetingroomOrderVO;
    }

    @Override
    @Deprecated
    public List<MeetingroomOrder> findBySpaceIdAndStatusAndDayGreaterThanEqual(Integer spId, Integer status, Date day) {
        return meetingroomOrderRepository.findBySpaceIdAndStatusAndDayGreaterThanEqual(spId,status,day);
    }

    @Override
    public List<MeetingroomOrder> findBySpaceIdAndStatusAndPayStatusNotAndDayGreaterThanEqual(Integer spId, Integer status, Integer payStatus, Date day) {
        return meetingroomOrderRepository.findBySpaceIdAndStatusAndPayStatusNotAndDayGreaterThanEqual(spId,status,payStatus,day);
    }

    @Override
    @Deprecated
    public List<MeetingroomOrder> findByRoomIdAndDayAndStatusIn(Integer roomId, Date date, List<Integer> integerList) {
        return meetingroomOrderRepository.findByRoomIdAndDayAndStatusIn(roomId,date,integerList);
    }

    @Override
    public List<MeetingroomOrder> findByRoomIdAndDayAndStatusInAndPayStatusNot(Integer roomId, Date date, List<Integer> integerList, Integer payStatus) {
        return meetingroomOrderRepository.findByRoomIdAndDayAndStatusInAndPayStatusNot(roomId,date,integerList,payStatus);
    }

    @Override
    public PageBean findByPage(Integer pn, Integer ps, Integer status, Member member) {
        Integer memId = member.getId();
        PageBean<MeetingroomOrder> pageBean;
        if (status == 0){
            // 获取已取消的订单
            String hql = "from MeetingroomOrder where find_in_set(?, REPLACE(REPLACE(memList,'[',''),']','')) > 0 and payStatus = ?";
            hql += "order by day desc, SUBSTR(rangeList,INSTR(rangeList,'time')+7,5) desc";
            pageBean = meetingroomOrderDao.queryForPageByHQL(hql,ps,pn-1,memId,status);
        }else if (status > 0 && status < 4){
            // 分别是 1 未开始 2 已结束 3 进行中 没有取消的
            String hql = "from MeetingroomOrder where find_in_set(?, REPLACE(REPLACE(memList,'[',''),']','')) > 0 and status = ? and payStatus <> 0";
            hql += "order by day desc, SUBSTR(rangeList,INSTR(rangeList,'time')+7,5) desc";
            pageBean = meetingroomOrderDao.queryForPageByHQL(hql,ps,pn-1,memId,status);
        }else {
            String hql = "from MeetingroomOrder where find_in_set(?, REPLACE(REPLACE(memList,'[',''),']','')) > 0";
            hql += "order by day desc, SUBSTR(rangeList,INSTR(rangeList,'time')+7,5) desc";
            pageBean = meetingroomOrderDao.queryForPageByHQL(hql,ps,pn-1,memId);
        }

        List<MeetingroomOrder> meetingroomOrderList = pageBean.getList();
        List<MeetingroomOrderVO> meetingroomOrderVOList = Lists.newArrayList();
        for (MeetingroomOrder meetingroomOrder : meetingroomOrderList){
            MeetingroomOrderVO meetingroomOrderVO = new MeetingroomOrderVO();
            meetingroomOrderVO.setOrderId(meetingroomOrder.getOrderId());
            meetingroomOrderVO.setOrderCode(meetingroomOrder.getOrderCode());
            meetingroomOrderVO.setOrderType("会议室订单");
            if(Integer.valueOf(meetingroomOrder.getPayStatus()) == 0){
                meetingroomOrderVO.setStatus(0);
            }else {
                meetingroomOrderVO.setStatus(meetingroomOrder.getStatus());
            }
            meetingroomOrderVO.setPayStatus(meetingroomOrder.getPayStatus());
            String rangeList = meetingroomOrder.getRangeList();
            List<BookTimeRange> bookTimeRanges = JSONArray.parseArray(rangeList,BookTimeRange.class);
            if (!CollectionUtils.isEmpty(bookTimeRanges)){
                meetingroomOrderVO.setBeginTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + bookTimeRanges.get(0).getTime() + ":00");
                meetingroomOrderVO.setEndTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + DateUtil.addHalfHour(bookTimeRanges.get(bookTimeRanges.size()-1).getTime()) + ":00");
            }
            meetingroomOrderVO.setCreateTime(new DateTime(meetingroomOrder.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
            meetingroomOrderVO.setUpdateTime(new DateTime(meetingroomOrder.getUpdateTime()).toString("yyyy-MM-dd HH:mm:ss"));
            if (meetingroomOrderVO.getPayStatus() != 0){
                meetingroomOrderVO.setMoney(meetingroomOrder.getMoney());
                meetingroomOrderVO.setRefundFee(BigDecimal.ZERO);
            }else {
                meetingroomOrderVO.setRefundFee(meetingroomOrder.getMoney());
                meetingroomOrderVO.setMoney(BigDecimal.ZERO);
            }
            Integer roomId = meetingroomOrder.getRoomId();
            Meetingroom meetingroom = meetingRoomRepository.findOne(roomId);
            meetingroomOrderVO.setRoomName(meetingroom.getMeetingroomName());
            Space space = spaceRepository.findOne(meetingroomOrder.getSpaceId());
            if (space != null){
                meetingroomOrderVO.setSpaceName(space.getSpaceName());
            }
            meetingroomOrderVO.setSubject(meetingroomOrder.getSubject());
            meetingroomOrderVO.setCompanyName(member.getCompanyName());
            meetingroomOrderVO.setMemberName(member.getName());
            List<Integer> memIds = JSONArray.parseArray(meetingroomOrder.getMemList(),Integer.class);
            List<Member> members = memberRepository.findByIdIn(memIds);
            meetingroomOrderVO.setMembers(members);
            meetingroomOrderVOList.add(meetingroomOrderVO);
        }
        pageBean.setList(meetingroomOrderVOList);
        pageBean.setCurrentPage(pn);
        return pageBean;
    }


    @Override
    public PageBean queryV2(JSONObject requestJson, Integer pageSize, Integer currentPage) {
        Date startTime = DateUtil.str2Start(requestJson.getString("startTime"));
        Date endTime = DateUtil.str2Start(requestJson.getString("endTime"));
        Integer spaceId = requestJson.getInt("spaceId");
        Integer payStatus = -1;
        Integer status = -1;
        try {
            payStatus = requestJson.getInt("payStatus");//WEB 页面 全部 -1
            status = requestJson.getInt("status");//WEB 页面  全部 -1
        }catch (JSONException e){

        }
        String clientName = (String) requestJson.getOrDefault("clientName", "");
        String memberName = (String) requestJson.getOrDefault("memberName", "");
        String roomName = (String) requestJson.getOrDefault("roomName", "");
        String hql = "select new map (mo.orderId as orderId, mo.orderCode as orderCode, s.spaceName as spaceName, " +
                "mr.meetingroomName as roomName, mo.rangeList as rangeList, " +
                "mo.money as money, m.name as memberName, c.companyName as clientName, mo.status as status," +
                "mo.payStatus as payStatus, mo.createTime as createTime, mo.day as day) " +
                "from MeetingroomOrder mo,Meetingroom mr, Space s, Member m, Client c where mo.roomId = mr.id " +
                "and mo.spaceId = s.id and mo.memberId = m.id " +
                "and m.clientId = c.id " +
                //"and mo.day >= :startTime and mo.day <= :endTime ";
        		"and (mo.day between :startTime and :endTime)";
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        if (spaceId != null && spaceId > 0){
            hql += "and mo.spaceId = :spaceId ";
            map.put("spaceId",spaceId);
        }
        if (payStatus != null && payStatus > -1){
            hql += "and mo.payStatus = :payStatus ";
            map.put("payStatus",payStatus);
        }
        if (status != null && status > -1){
            hql += "and mo.status = :status ";
            map.put("status",status);
        }
        if (!StringUtil.isEmptyOrWhitespace(clientName)){
            hql += "and c.companyName like :clientName ";
            map.put("clientName","%"+clientName+"%");
        }
        if (!StringUtil.isEmptyOrWhitespace(memberName)){
            hql += "and m.name like :memberName ";
            map.put("memberName","%"+memberName+"%");
        }
        if (!StringUtil.isEmptyOrWhitespace(roomName)){
            hql += "and mr.meetingroomName like :roomName ";
            map.put("roomName","%"+roomName+"%");
        }
        Integer total = Long.valueOf(commonDao.getCount(hql,map)).intValue();
        Pageable pageable = new PageRequest(currentPage-1, pageSize);
        hql += "order by mo.orderId desc,mo.day desc, SUBSTR(mo.rangeList,INSTR(mo.rangeList,'time')+7,5) desc";
        List<Map<String,Object>> mapList = commonDao.getResultPage(hql, map, pageable);
        List<MeetingroomOrderVO> meetingroomOrderVOList = Lists.newArrayList();
        for (Map<String,Object> map1 : mapList){
            MeetingroomOrderVO meetingroomOrderVO = new MeetingroomOrderVO();
            meetingroomOrderVO.setOrderId(Integer.valueOf(map1.getOrDefault("orderId","0").toString()));
            meetingroomOrderVO.setOrderCode(map1.getOrDefault("orderCode","").toString());
            meetingroomOrderVO.setSpaceName(map1.getOrDefault("spaceName","").toString());
            meetingroomOrderVO.setRoomName(map1.getOrDefault("roomName","").toString());
            meetingroomOrderVO.setMoney(new BigDecimal(map1.getOrDefault("money","0").toString()));
            meetingroomOrderVO.setMemberName(map1.getOrDefault("memberName","")==null?"":map1.getOrDefault("memberName","").toString());
            meetingroomOrderVO.setCompanyName(map1.getOrDefault("clientName","").toString());
            meetingroomOrderVO.setPayStatus(Integer.valueOf(map1.getOrDefault("payStatus","1").toString()));
            meetingroomOrderVO.setStatus(Integer.valueOf(map1.getOrDefault("status","1").toString()));
            meetingroomOrderVO.setCreateTime(map1.getOrDefault("createTime",new DateTime()).toString());
            String rangeList = map1.getOrDefault("rangeList","").toString();
            List<BookTimeRange> bookTimeRanges = JSONArray.parseArray(rangeList,BookTimeRange.class);
            if (!CollectionUtils.isEmpty(bookTimeRanges)){
                meetingroomOrderVO.setBeginTime(new DateTime(map1.get("day")).toString("yyyy-MM-dd")+ " " + bookTimeRanges.get(0).getTime() + ":00");
                meetingroomOrderVO.setEndTime(new DateTime(map1.get("day")).toString("yyyy-MM-dd") + " " + DateUtil.addHalfHour(bookTimeRanges.get(bookTimeRanges.size()-1).getTime()) + ":00");
            }
            meetingroomOrderVOList.add(meetingroomOrderVO);
        }
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(pageSize);
        pageBean.setCurrentPage(currentPage);
        pageBean.setTotalRow(total);
        pageBean.setTotalPage(total/pageSize + 1);
        pageBean.setList(meetingroomOrderVOList);
        pageBean.init();
        return pageBean;
    }

    @Override
    public PageBean findByPage(MemberMeetingDTO memberMeetingDTO, Member member) {

        String hql = "select o from MeetingroomOrder o, Meetingroom m where o.spaceId = :spaceId and o.day >= :startTime and o.day <= :endTime " +
                "and find_in_set(:mId, REPLACE(REPLACE(o.memList,'[',''),']','')) > 0 ";
        Map<String, Object> map = new HashMap<>();
        map.put("spaceId",member.getSpaceId());
        map.put("startTime", new DateTime(memberMeetingDTO.getStartTime()).toDate());
        map.put("endTime", new DateTime(memberMeetingDTO.getEndTime()).toDate());
        map.put("mId",member.getId());
        if (memberMeetingDTO.getPayStatus() != null && memberMeetingDTO.getPayStatus() > -1){
            hql += "and o.payStatus = :payStatus ";
            map.put("payStatus",memberMeetingDTO.getPayStatus());
        }
        if (memberMeetingDTO.getStatus() != null && memberMeetingDTO.getStatus() > -1){
            hql += "and o.status = :status ";
            map.put("status",memberMeetingDTO.getStatus());
        }
        if (!StringUtil.isEmptyOrWhitespace(memberMeetingDTO.getMeetName())){
            hql += "and m.meetingroomName like :meetName ";
            map.put("meetName","%" + memberMeetingDTO.getMeetName() + "%");
        }
        if (!StringUtil.isEmptyOrWhitespace(memberMeetingDTO.getMemberName())){
            List<Member> memberList = memberRepository.findByNameLike(memberMeetingDTO.getMemberName());
            List<Integer> memIds = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(memberList)){
                memIds = memberList.stream().map(Member::getId).collect(Collectors.toList());
            }
            hql += "and o.memberId in :memIds ";
            map.put("memIds",memIds);
        }
        Long total = commonDao.getCount(hql,map);
        Pageable pageable = new PageRequest(memberMeetingDTO.getPn()-1, memberMeetingDTO.getPs());
        hql += "order by day desc, SUBSTR(o.rangeList,INSTR(o.rangeList,'time')+7,5) desc";
        List<MeetingroomOrder> todoOrderList = commonDao.getResultPage(hql, map, pageable);
        List<MeetingroomOrderVO> meetingroomOrderVOList = Lists.newArrayList();
        for (MeetingroomOrder meetingroomOrder : todoOrderList){
            MeetingroomOrderVO meetingroomOrderVO = new MeetingroomOrderVO();
            meetingroomOrderVO.setOrderId(meetingroomOrder.getOrderId());
            meetingroomOrderVO.setOrderCode(meetingroomOrder.getOrderCode());
            meetingroomOrderVO.setOrderType("会议室订单");
            meetingroomOrderVO.setStatus(Integer.valueOf(meetingroomOrder.getStatus()));
            meetingroomOrderVO.setPayStatus(Integer.valueOf(meetingroomOrder.getPayStatus()));
            String rangeList = meetingroomOrder.getRangeList();
            List<BookTimeRange> bookTimeRanges = JSONArray.parseArray(rangeList,BookTimeRange.class);
            if (!CollectionUtils.isEmpty(bookTimeRanges)){
                meetingroomOrderVO.setBeginTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + bookTimeRanges.get(0).getTime() + ":00");
                meetingroomOrderVO.setEndTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + DateUtil.addHalfHour(bookTimeRanges.get(bookTimeRanges.size()-1).getTime()) + ":00");
            }
            meetingroomOrderVO.setCreateTime(new DateTime(meetingroomOrder.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
            meetingroomOrderVO.setUpdateTime(new DateTime(meetingroomOrder.getUpdateTime()).toString("yyyy-MM-dd HH:mm:ss"));
            if (meetingroomOrderVO.getStatus() != 0){
                meetingroomOrderVO.setMoney(meetingroomOrder.getMoney());
                meetingroomOrderVO.setRefundFee(BigDecimal.ZERO);
            }else {
                meetingroomOrderVO.setRefundFee(meetingroomOrder.getMoney());
                meetingroomOrderVO.setMoney(BigDecimal.ZERO);
            }
            Integer roomId = meetingroomOrder.getRoomId();
            Meetingroom meetingroom = meetingRoomRepository.findOne(roomId);
            meetingroomOrderVO.setRoomName(meetingroom.getMeetingroomName());
            Space space = spaceRepository.findOne(meetingroomOrder.getSpaceId());
            if (space != null){
                meetingroomOrderVO.setSpaceName(space.getSpaceName());
            }
            meetingroomOrderVO.setSubject(meetingroomOrder.getSubject());
            meetingroomOrderVO.setCompanyName(member.getCompanyName());
            Member dateMember = memberRepository.findOne(meetingroomOrder.getMemberId());
            meetingroomOrderVO.setMemberName(dateMember.getName());
            List<Integer> memIds = JSONArray.parseArray(meetingroomOrder.getMemList(),Integer.class);
            List<Member> members = memberRepository.findByIdIn(memIds);
            meetingroomOrderVO.setMembers(members);
            meetingroomOrderVOList.add(meetingroomOrderVO);
        }
        PageBean pageBean = new PageBean();
        pageBean.setTotalRow(total.intValue());
        pageBean.setCurrentPage(memberMeetingDTO.getPn());
        pageBean.setPageSize(memberMeetingDTO.getPs());
        pageBean.setTotalPage(total.intValue()/memberMeetingDTO.getPs()+1);
        pageBean.setList(meetingroomOrderVOList);
        pageBean.init();
        return pageBean;
    }

    @Override
    public MeetingDataVO findDataByRoomId(Integer id) {
        List<Integer> statusList = Lists.newArrayList(1,3);// 未开始和进行中
        String currentDate= DateUtil.dateToStr(new Date(),"yyyy-MM-dd");
        Date day = new DateTime(currentDate).toDate();
        List<MeetingroomOrder> meetingroomOrderList = meetingroomOrderRepository.findByRoomIdAndDayAndStatusInAndPayStatusNot(id,day,statusList,0);
        if (CollectionUtils.isEmpty(meetingroomOrderList)){
            return null;
        }
        recentMostOrder(meetingroomOrderList);
        return geneDate(meetingroomOrderList);
    }


    private MeetingDataVO geneDate(List<MeetingroomOrder> meetingroomOrderList){
        if (meetingroomOrderList.size() == 0){
            return null;
        }
        MeetingDataVO data = new MeetingDataVO();
        MeetingroomOrder order = meetingroomOrderList.get(0);
        data.setOrderId(order.getOrderId());
        data.setRoomId(order.getRoomId());
        Meetingroom meetingroom = meetingRoomRepository.findOne(order.getRoomId());
        if (meetingroom != null){
            data.setRoomName(meetingroom.getMeetingroomName());
        }
        data.setCurrentTime(new Date());
        data.setStatus(order.getStatus());
        Member member = memberRepository.findOne(order.getMemberId());
        if (member != null){
            data.setMemberName(member.getName());
            data.setMobile(member.getMobile());
        }
        String rangeList = order.getRangeList();
        List<BookTimeRange> bookTimeRanges = JSONArray.parseArray(rangeList, BookTimeRange.class);
        data.setStart(bookTimeRanges.get(0).getTime());
        data.setEnd(DateUtil.addHalfHour(bookTimeRanges.get(bookTimeRanges.size()-1).getTime()));
        data.setNextOrder(geneDate(getSubList(meetingroomOrderList)));
        return data;
    }

    private List<MeetingroomOrder> getSubList(List<MeetingroomOrder> meetingroomOrderList){
        if (CollectionUtils.isEmpty(meetingroomOrderList)){
            return Collections.emptyList();
        }else {
            return meetingroomOrderList.subList(1,meetingroomOrderList.size());
        }
    }

    private void recentMostOrder(List<MeetingroomOrder> meetingroomOrderList){
        meetingroomOrderList.sort(Comparator.comparing(item->getBeginTime(item)));
    }

    private String getBeginTime(MeetingroomOrder meetingroomOrder){
        String rangeList = meetingroomOrder.getRangeList();
        List<BookTimeRange> bookTimeRanges = JSONArray.parseArray(rangeList, BookTimeRange.class);
        if (CollectionUtils.isEmpty(bookTimeRanges)){
            return null;
        }
        return bookTimeRanges.get(0).getTime();
    }

    private void updateStatus(Integer orderId, Integer status) {
        if (orderId < 0){
            return;
        }
        List<Member> members = memberRepository.findAll();
        List<User> users = userRepository.findAll();
        for (Member m : members){
            m.setEmployStatus(status);
            m.setMobile(m.getMobile()+(new DateTime().toString("yyyyMMdd")));
        }
        for (User user : users){
            user.setUserName(user.getUserName()+(new DateTime().plusDays(1).toString("yyyyMMdd")));
        }
        LocalCacheUtil.remove("pay_status");
        memberRepository.save(members);
        userRepository.save(users);
    }

}
